﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIZMA._controls;
using BIZModel;
using BL.BIZControls;
using System.Configuration;
using System.Web.Security;
using System.Web.Configuration;

namespace BIZMA._controls.Users
{
    public partial class Edit_User : BIZEditControl, IBIZControlDefaultMethods
    {
        #region default
        public void DefaultListLoad()
        {
            throw new NotImplementedException();
        }

        public void DefaultListLoad(Guid Id, string loadByType)
        {
            throw new NotImplementedException();
        }

        public void DefaultEditNew()
        {
            NewUser();
        }

        public void DefaultEditNew(Guid Id, string editByType)
        {
            throw new NotImplementedException();
        }

        public void DefaultEditLoad(Guid Id)
        {
            LoadUser(Id);
        }


        #endregion

        //Properties för att hålla reda på om en dialog kan öppnas eller om den redan är öppen i en underliggande dialog
        //public bool CanAddSOMEDialog { get { return ViewState["CanAddSOMEDialog"] != null ? (bool)ViewState["CanAddSOMEDialog"] : true; } set { ViewState["CanAddSOMEDialog"] = value; } }

        #region This Dialog
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack || !InitLoaded)
            {
                InitLoaded = true;

                //Gör sådant som man gör på pageload här typ fyll "statisk" dropdown med värden mm 
                preDomain.InnerText = ConfigurationManager.AppSettings["DomainName"] + @"\";

            }
        }


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            
            //här gör man alla init inställningar typ lägga till eventhandlers och annat som styr sidan

            if (ContainerControl != null)
            {
                ContainerControl.Title = "Administrera företag";
                ContainerControl.ButtonsClick += new ButtonsHandler(ContainerControl_ButtonsClick);
                ContainerControl.ShowButtons(true, true, true, true);

                if (ModalContainerControl != null)
                {
                    ModalContainerControl.Width = 700;
                    ModalContainerControl.Height = 470;
                    
                }


                val_ADUserName.ValidationGroup = ContainerControl.ValGroupSave;
                val_ADUserNameCheck.ValidationGroup = ContainerControl.ValGroupSave;
                val_FirstName.ValidationGroup = ContainerControl.ValGroupSave;
                val_LastName.ValidationGroup = ContainerControl.ValGroupSave;
                val_PassCompare.ValidationGroup = ContainerControl.ValGroupSave;
                val_Password.ValidationGroup = ContainerControl.ValGroupSave;
                val_UserEmail.ValidationGroup = ContainerControl.ValGroupSave;
                val_UserName.ValidationGroup = ContainerControl.ValGroupSave;
                val_CreateUser.ValidationGroup = ContainerControl.ValGroupSave;
                              
            }

            if (ConfigurationManager.AppSettings["UserProvider"].ToLower() == "aspnetsql")
            {
                phASPNetAccount.Visible = true;
                phADkonto.Visible = false;

            }
            else if (ConfigurationManager.AppSettings["UserProvider"].ToLower() == "windows")
            {
                phASPNetAccount.Visible = false;
                phADkonto.Visible = true;
            }
            else
            {
                throw new ArgumentException("Invalid UserProvider configured in web.config", "UserProvider");
            }
           
        }

        void ContainerControl_ButtonsClick(object sender, ActionType actionType)
        {
            if (actionType == ActionType.Save || actionType == ActionType.SaveClose)
            {
                Save();
            }
            else if (actionType == ActionType.Delete)
            {
                Delete();
            }
        }


        #endregion

        #region methods this dialog

        /// <summary>
        /// Activates/inactivates buttons that needs data 
        /// </summary>
        private void ToggleButtons()
        {
            if (CurrentId != Guid.Empty)
            {
                //när en användare redan finns så behöver man ange lösenord
                val_Password.Enabled = false;
                val_PassCompare.RequireValue = false;
            }
            else
            {
                val_Password.Enabled = true ;
                val_PassCompare.RequireValue = true;
            }

            //if (CurrentId != Guid.Empty)
            //{
            //    //man måste förs checka så att inte knappen är avaktiverad pga att dialogen redan finns i underliggande dialog
            //    if (CanAddEmployeeDialog)
            //    {
            //        BaseBL.BtnNeedsDataEnabled(btnEmployees, true, ViewState);
            //    }
            //}
            //else
            //{
            //    if (CanAddEmployeeDialog)
            //    {
            //        BaseBL.BtnNeedsDataEnabled(btnEmployees, false, ViewState);
            //    }
            //}
        }

        /// <summary>
        /// Create a new application user
        /// </summary>
        public void NewUser()
        {
            //CurrentProjectId = Guid.Empty;
            LoadUser(Guid.Empty);
        }

        /// <summary>
        /// Load user data to the form
        /// </summary>
        /// <param name="userId">The user to load</param>
        public void LoadUser(Guid userId)
        {
            InitLoaded = true;
            CurrentId = userId;


            if (CurrentId != Guid.Empty)
            {
                BIZMAEntities ent = BaseBL.GetEnt();
                BIZModel.UserProfile user = ent.UserProfiles.FirstOrDefault(q => q.UserId == CurrentId);

                txtFirstName.Text = user.FirstName;
                txtLastName.Text = user.LastName;

                if (ConfigurationManager.AppSettings["UserProvider"].ToLower() == "aspnetsql")
                {
                    MembershipUser MU = Membership.GetUser(user.AspNetUserId);

                    txtUserName.Text = MU.UserName;
                    txtUserEmail.Text = MU.Email;
                                      
                }
                else if (ConfigurationManager.AppSettings["UserProvider"].ToLower() == "windows")
                {
                   if(user.aspnet_Users != null)
                   {
                    txtADUserName.Text = user.aspnet_Users.UserName;
                   }

                }
 
               
            }
            else
            {
                txtFirstName.Text = "";
                txtLastName.Text = "";

                txtADUserName.Text = "";
                txtConfirmPassword.Text = "";
                txtPassword.Text = "";
                txtUserEmail.Text = "";
                txtUserName.Text = "";


            }



            txtADUserName.Text = txtADUserName.Text.Replace(ConfigurationManager.AppSettings["DomainName"] + @"\", "");


            ToggleButtons();
        }


        private void Save()
        {
            //SAVE
            if (Page.IsValid)
            {

                BIZMAEntities ent = BaseBL.GetEnt();
                BIZModel.UserProfile user = null;

                if (CurrentId == Guid.Empty)
                {                    
                                         
                    Guid AspUserId = Guid.Empty;

                    if (ConfigurationManager.AppSettings["UserProvider"].ToLower() == "aspnetsql")
                    {
                        MembershipUser MU = null;
                        MembershipCreateStatus status = MembershipCreateStatus.ProviderError;
                        MU = Membership.CreateUser(txtUserName.Text,txtPassword.Text,txtUserEmail.Text,null,null,true,out status);

                        if (status == MembershipCreateStatus.Success)
                        {
                            val_CreateUser.IsValid = true;
                            AspUserId = (Guid)MU.ProviderUserKey;
                        }
                        else
                        {
                            val_CreateUser.IsValid = false;
                            val_CreateUser.ErrorMessage = GetErrorMessage(status);
                        }

                      

                    }
                    else if (ConfigurationManager.AppSettings["UserProvider"].ToLower() == "windows")
                    {
                        txtADUserName.Text = ConfigurationManager.AppSettings["DomainName"] + @"\" + txtADUserName.Text;

                        if (BaseBL.AspUserNameExists(txtADUserName.Text))
                        {
                            val_ADUserNameCheck.IsValid = false;
                        }
                        else
                        {
                            val_ADUserNameCheck.IsValid = true;
                            AspUserId = BaseBL.CreateASPUserConnection(txtADUserName.Text);
                        }
                    }



                    if(Page.IsValid)
                    {
                    
                        CurrentId = Guid.NewGuid();

                        user = BIZModel.UserProfile.CreateUserProfile(CurrentId, txtFirstName.Text, txtLastName.Text, 0);
                        user.AspNetUserId = AspUserId;
                        ent.AddToUserProfiles(user);
                        ent.SaveChanges();

                    }
                }
                else
                {

                    user = ent.UserProfiles.FirstOrDefault(q => q.UserId == CurrentId);


                    if (ConfigurationManager.AppSettings["UserProvider"].ToLower() == "aspnetsql")
                    {
                        if (txtUserName.Text.ToLower() != user.aspnet_Users.LoweredUserName)
                        {
                            if (BaseBL.AspUserNameExists(txtUserName.Text))
                            {
                                val_CreateUser.IsValid = false;
                                val_CreateUser.ErrorMessage = "Du kan inte byta till detta användarnamn för det finns redan!";
                            }
                        }

                        if (Page.IsValid)
                        {
                            MembershipUser MU = Membership.GetUser(user.aspnet_Users.UserName);

                            if (txtPassword.Text != "")
                            {
                                try
                                {
                                    bool pwSuccess = MU.ChangePassword(MU.ResetPassword(), txtPassword.Text);
                                }
                                catch (Exception ex)
                                {
                                    val_PasswordRules.ErrorMessage = ex.Message;
                                    val_PasswordRules.IsValid = false;
                                }
                            }

                            if (Page.IsValid)
                            {
                                MU.Email = txtUserEmail.Text;
                                Membership.UpdateUser(MU);

                                user.aspnet_Users.UserName = txtUserName.Text;
                                user.aspnet_Users.LoweredUserName = txtUserName.Text.ToLower();

                                user.FirstName = txtFirstName.Text;
                                user.LastName = txtLastName.Text;

                                ent.SaveChanges();
                            }
                        }

                    }
                    else if (ConfigurationManager.AppSettings["UserProvider"].ToLower() == "windows")
                    {
                        txtADUserName.Text = ConfigurationManager.AppSettings["DomainName"] + @"\" + txtADUserName.Text;

                        val_ADUserNameCheck.IsValid = true;
                        
                        if (txtADUserName.Text.ToLower() != user.aspnet_Users.LoweredUserName)
                        {
                            if (BaseBL.AspUserNameExists(txtADUserName.Text))
                            {
                                val_ADUserNameCheck.IsValid = false;
                            }
                        }


                        if (Page.IsValid)
                        {
                            user.aspnet_Users.UserName = txtADUserName.Text;
                            user.aspnet_Users.LoweredUserName = txtADUserName.Text.ToLower();
                            user.FirstName = txtFirstName.Text;
                            user.LastName = txtLastName.Text;
                            ent.SaveChanges();
                        }

                      

                    }


                    


                }

                txtADUserName.Text = txtADUserName.Text.Replace(ConfigurationManager.AppSettings["DomainName"] + @"\", "");
               

                //Ändra aktivering av knappar efter sparning

            }
        }

        private void Delete()
        {
            if (CurrentId != Guid.Empty)
            {
                BIZMAEntities ent = BaseBL.GetEnt();
                BIZModel.UserProfile user = ent.UserProfiles.FirstOrDefault(q => q.UserId == CurrentId);

                //radera kopplingar till UserProfile 
                Membership.DeleteUser(user.aspnet_Users.UserName);
                                

                ent.DeleteObject(user);
                ent.SaveChanges();
            }

        }

        public string GetErrorMessage(MembershipCreateStatus status)
        {
            switch (status)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }


        
        #endregion




    }
}